package com.criticalbotch.ijnition.checkers;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import org.json.JSONException;
import org.json.JSONObject;

import com.criticalbotch.ijnition.TagManager;

public class TagChecker extends Thread {

	String urlString;
	TagManager tagManager;
	int waitTime;

	public TagChecker(String url, TagManager manager, int wait) {
		setUrlString(url);
		setTagManager(manager);
		setWaitTime(wait);
	}

	private void setTagManager(TagManager manager) {
		tagManager = manager;
	}

	private void setWaitTime(int t) {
		waitTime = t;
	}

	private int getWaitTime() {
		return waitTime;
	}

	public void setUrlString(String url) {
		urlString = url;
	}

	String getUrlString() {
		if (urlString.startsWith("http://"))
			return urlString;
		else
			return "http://" + urlString;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub

		// System.out.println("Checker running...");
		// System.out.println("Check Period: " + getWaitTime());

		try {
			getUserJSON();
		} catch (MalformedURLException mfurl) {
			System.err.println("Provided URL is not a proper URL");
			mfurl.printStackTrace();
		} catch (IOException ioe) {
			// System.err.println("Provided URL is not a proper URL");
			ioe.printStackTrace();
		} catch (JSONException je) {
			je.printStackTrace();
		}

		notifyFinished();
	}

	public void notifyFinished() {
		try {
			sleep(getWaitTime());
		} catch (Exception e) {
			e.printStackTrace();
		}

		// System.out.println("Checker finished.");

		tagManager.notifiedTagCheck();
	}

	void getUserJSON() throws MalformedURLException, IOException, JSONException {

		URL userURL = new URL(getUrlString());
		BufferedReader in = new BufferedReader(new InputStreamReader(
				userURL.openStream()));
		BufferedWriter out = new BufferedWriter(new FileWriter(new File(
				"get-tags.json")));
		JSONObject json = new JSONObject(in.readLine());
		in.close();
		out.write(json.toString(2));
		out.close();
	}

	public TagManager getTagManager() {
		return tagManager;
	}

}
